<?php

namespace app\util;

class RouteUtil
{
    /**
     * 格式化路由数据以适配前端框架
     * @param array $routes 路由数据数组
     * @return array 格式化后的路由数据
     */
    public static function format($routes)
    {
        if (empty($routes)) {
            return [];
        }

        $routes = self::buildRouteTree($routes);
        return self::formatRoutes($routes);
    }

    /**
     * 递归格式化路由数据
     * @param array $routes 路由数据
     * @return array 格式化后的路由数据
     */
    private static function formatRoutes($routes)
    {
        $formattedRoutes = [];
        foreach ($routes as $route) {
            // 解析meta字段
            $meta = $route['meta'] ?? [];
            if ($meta instanceof \think\collection\Collectable || $meta instanceof \ArrayAccess) {
                $meta = (array)$meta;
            }

            $clientType = strtolower((string) ($route['client_type'] ?? $meta['clientType'] ?? 'admin'));
            $showLink = (int) ($route['is_visible'] ?? 1) === 1;
            $showParent = $meta['showParent'] ?? true;

            $formattedRoute = [
                'id' => $route['id'],
                'parent_id' => $route['parent_id'],
                'identifier' => $route['identifier'] ?? null,
                'path' => $route['path'] ?? '',
                'name' => $route['name'] ?? '',
                'component' => $route['component'] ?? '',
                'redirect' => $route['redirect'] ?? '',
                'meta' => [
                    'title' => $meta['title'] ?? ($route['name'] ?? ''),
                    'icon' => $meta['icon'] ?? '',
                    'rank' => $meta['rank'] ?? 0,
                    'showLink' => $showLink,
                    'showParent' => (bool) $showParent,
                    'clientType' => $clientType,
                    'roles' => $meta['roles'] ?? null,
                ]
            ];

            // 递归处理子路由
            $formattedChildren = [];
            if (!empty($route['children'])) {
                $formattedChildren = self::formatRoutes($route['children']);
                if (!empty($formattedChildren)) {
                    $formattedRoute['children'] = $formattedChildren;
                }
            }

            // 顶级目录若没有可用子菜单则跳过（避免空壳菜单）
            $isTopLevel = isset($route['parent_id']) && (int) $route['parent_id'] === 0;
            $isLayoutOnly = empty($route['component']) || strtolower((string) $route['component']) === 'layout';
            if ($isTopLevel && $isLayoutOnly && empty($formattedChildren)) {
                continue;
            }

            $formattedRoutes[] = $formattedRoute;
        }

        return $formattedRoutes;
    }

    /**
     * 构建路由树结构
     * @param array $routes 路由数据
     * @param int $parentId 父级ID
     * @return array 树形结构的路由数据
     */
    private static function buildRouteTree($routes, $parentId = 0)
    {
        $tree = [];
        foreach ($routes as $route) {
            if (isset($route['parent_id']) && $route['parent_id'] == $parentId) {
                $children = self::buildRouteTree($routes, $route['id']);
                if (!empty($children)) {
                    $route['children'] = $children;
                }
                $tree[] = $route;
            }
        }
        return $tree;
    }
}
